package com.beimihu.GetAFData.controller;



import com.beimihu.GetAFData.util.AesException;
import com.beimihu.GetAFData.util.HttpRequestor;
import com.beimihu.GetAFData.util.WXBizMsgCrypt;
import com.beimihu.GetAFData.util.api.WeChatApi;
import com.beimihu.GetAFData.data.AccessToken;
import com.beimihu.GetAFData.domain.AFData;
import com.beimihu.GetAFData.service.GetAFDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * @auther beimihu
 * @date 2024/1/29
 * @description
 */
@Controller
@RequestMapping("/api/wx")
public class WxController {

    private static final Logger log = LoggerFactory.getLogger(WxController.class);

    @Value("${wx.sToken}")
    private String sToken;

    @Value("${wx.sCorpID}")
    private String sCorpID;

    @Value("${wx.sEncodingAESKey}")
    private String sEncodingAESKey;


    @Autowired
    public GetAFDataService getAFDataService;


    private String prefix = "api/wx";

    String verifyTAG = "verifyUrl";
    String sendMsgTAG  = "sendMsg";
    String getTokenTAG = "getToken";

    @GetMapping("/verifyUrl")
    @ResponseBody
    public String verifyUrl(
            @RequestParam("msg_signature") String msgSignature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr ) throws UnsupportedEncodingException, AesException {

        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(sToken,sEncodingAESKey,sCorpID);

        msgSignature = URLDecoder.decode(msgSignature, "UTF-8");
        timestamp = URLDecoder.decode(timestamp, "UTF-8");
        nonce = URLDecoder.decode(nonce, "UTF-8");

        log.info(verifyTAG,"msgSignature:"+msgSignature);
        log.info(verifyTAG,"timestamp:"+timestamp);
        log.info(verifyTAG,"nonce:"+nonce);
        log.info(verifyTAG,"echostr:"+echostr);

        String sEchoStr;
        sEchoStr = wxBizMsgCrypt.VerifyURL(msgSignature,timestamp,nonce,echostr);
        log.info(verifyTAG,"VerifyURL   sEchoStr:"+sEchoStr);
        return sEchoStr;
    }

    @PostMapping("/sendMsg")
    @ResponseBody
    public String sendMsg() throws Exception {
        WxController wxController = new WxController();

        String accessToken = "";
        log.info(sendMsgTAG,"accessToken:"+accessToken);

        AFData afData = new AFData();
        List<AFData> afDataList = getAFDataService.selectAFDataList(afData);
        String msg = afDataList.get(0).getMsg();
//        String encodedMsg = URLEncoder.encode(msg, StandardCharsets.UTF_8.toString());

        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken;
        String params = "{\n" +
                "   \"touser\" : \"beimihu\",\n" +
                "   \"msgtype\" : \"text\",\n" +
                "   \"agentid\" : 1000002,\n" +
                "   \"text\" : {\n" +
                "       \"content\" : \""+msg+"\"\n" +
                "   },\n" +
                "   \"safe\":0,\n" +
                "   \"enable_id_trans\": 0,\n" +
                "   \"enable_duplicate_check\": 0,\n" +
                "   \"duplicate_check_interval\": 1800\n" +
                "}";

        log.info(sendMsgTAG,"params:"+params);
        HttpRequestor httpRequestor = new HttpRequestor();
        String result = httpRequestor.sendPostRequest(url,params);

        return result;
    }

    @PostMapping("/getToken")
    @ResponseBody
    public AccessToken getAccessToken(){
        WeChatApi weChatApi = new WeChatApi();
        AccessToken accessToken =  weChatApi.getAccessToken();
        log.info(getTokenTAG,"getAccessToken Class");
        log.info(getTokenTAG,"accessToken:"+accessToken);
        return accessToken;
    }


    @PostMapping("/createGroup")
    @ResponseBody
    public String createGroup(){
        String accessToken = "";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token="+accessToken;
        String params = "{\n" +
                "    \"name\" : \"消息通知群\",\n" +
                "    \"userlist\" : [\"beimihu\"],\n" +
                "    \"chatid\" : \"123\",\n" +
                "}";

        log.info(sendMsgTAG,"params:"+params);
        HttpRequestor httpRequestor = new HttpRequestor();
        String result = httpRequestor.sendPostRequest(url,params);
        return result;
    }

    @PostMapping("/sendMsgToGroup")
    @ResponseBody
    @Scheduled(cron = "0 2 12,19,23 * * ? ")
    public String sendMsgToGroup(){
        AFData afData = new AFData();
        List<AFData> afDataList = getAFDataService.selectAFDataList(afData);
        String msg = afDataList.get(0).getMsg();
        getAFDataService.deleteData();
        WxController controller = new WxController();
        AccessToken accessToken =  controller.getAccessToken();
        String token = accessToken.getAccess_token();
//        String accessToken = "J6VxZ6di7lHB0PQYCC4js5kqG51grByTSEsq5Q7HkICQivfUZ99yUjCcNIWw6aj3pXbPbwFct2TLlNAznfDxoLcXF5dQWwlyXpYhZ9qpcwATRPPtYjoIiECOanUGKmd-28nDQgKO-dU6Fvz1ArVYJcO_VIicVivW5PmpnRWo5Tx_EMjXfXBaFlpEgPK7v-NP0nLGFTCSmoBZXYdW0xQKmw";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token="+token;
        String params = "{\n" +
                "\t\"chatid\": \"123\",\n" +
                "\t\"msgtype\":\"text\",\n" +
                "\t\"text\":{\n" +
                "\t\t\"content\" : \""+msg+"\"\n" +
                "\t},\n" +
                "\t\"safe\":0\n" +
                "}";

        log.info(sendMsgTAG,"params:"+params);
        HttpRequestor httpRequestor = new HttpRequestor();
        String result = httpRequestor.sendPostRequest(url,params);
        return result;
    }
}
